"""
    自动化架构体系
    数据驱动运行入口
    Powered By jiachangwei
    2020/4/3
"""
import inspect,time
import os

from app.appkeys import App
from common.NewExcel import Reader, Writer
from common.excelresult import Res
from common.mail import Mail
#from common.mysql import Mysql
from common.txt import Txt
from inter.interKeys import HTTP, SOAP
from common import logger, config
from common import Encrypt
from web.webkeys import Web
from inter.commonKeys import sysKey


logger.info("开始运行")

sysKey.path = os.path.dirname(__file__)

# 数据驱动运行
def getfunc(obj, method):
    """
    反射获取函数和参数列表
    :param obj: 对象
    :param method: 方法名
    :return:
    """
    try:
        func = getattr(obj, method)
    except Exception as e:
        return None

    arg = inspect.getfullargspec(func).__str__()
    arg = arg[arg.find('args=') + 5:arg.find(', varargs')]
    arg = eval(arg)
    arg.remove('self')
    return func, len(arg)


def runcase(obj, line):
    if len(line[0]) > 0 or len((line[1])) > 0:
        # 分组信息不执行
        return

    func = getfunc(obj, line[3])
    if func is None:
        logger.warn("关键字%s不存在" % line[3])
        return

    if func[1] == 0:
        func[0]()
    elif func[1] == 1:
        func[0](line[4])
    elif func[1] == 2:
        func[0](line[4], line[5])
    elif func[1] == 3:
        func[0](line[4], line[5], line[6])
    else:
        logger.warn("关键字暂不支持超过3个参数")


# 初始化配置
config.get_config('./lib/conf/conf.properties')
# # 初始化数据库
# mysql = Mysql()
# mysql.init_mysql('./lib/conf/userinfo.sql')


# 启用加密
Encrypt.init()

casename = 'HTTP接口用例-all'

reader = Reader()
reader.open_excel('./lib/%s.xlsx' % casename)
writer = Writer()
writer.copy_open('./lib/%s.xlsx' % casename, './lib/result-%s.xlsx' % casename)
sheetname = reader.get_sheets()
# 写开始时间
starttime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
writer.set_sheet(sheetname[0])
writer.write(1,3,starttime)

# 运行的实例对象，默认是HTTP
http = HTTP(writer)
soap = SOAP(writer)
web = Web(writer)
app = App(writer)
obj = http


for sheet in sheetname:
    # 设置当前读取的sheet页面
    reader.set_sheet(sheet)
    writer.set_sheet(sheet)

    # openpyxl
    lines = reader.readline()

    # 分用例类型执行
    line = lines[1]
    if line[1] == "HTTP":
        obj = http
    elif line[1] == "SOAP":
        obj = soap
    elif line[1] == "WEB":
        obj = web
    elif line[1] == "APP":
        obj = app

    for i in range(reader.rows):
        obj.row = i
        line = lines[i]
        logger.info(line)
        runcase(obj, line)


# 写结束时间
endtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
writer.set_sheet(writer.get_sheets()[0])
writer.write(1,4,endtime)
writer.save_close()


# 获取结果数据
res = Res()
summary = res.get_res('./lib/result-%s.xlsx' % casename)
logger.info(summary)
groups = res.get_groups('./lib/result-%s.xlsx' % casename)
logger.info(groups)

txt = Txt('./lib/conf/' + config.config['mailtxt'])
html = txt.read()[0]

# 替换汇总信息
for key in summary.keys():
    if summary[key]=="Pass":
        html = html.replace('<td height="28" bgcolor="#FFFFFF" align="center" style="border:1px solid #ccc;">status</td>',
                     '<td height="28" bgcolor="#FFFFFF" align="center" style="border:1px solid #ccc;color:blue;">Pass</td>')
    elif summary[key]=="Fail":
        html = html.replace('<td height="28" bgcolor="#FFFFFF" align="center" style="border:1px solid #ccc;">status</td>',
                     '<td height="28" bgcolor="#FFFFFF" align="center" style="border:1px solid #ccc;color:red;">Fail</td>')
    else:
        html = html.replace(key,summary[key])

# 获取分组显示
tr = '<tr><td width="100" height="28" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">分组信息</td><td width="80" height="28" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">用例总数</td><td width="80" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">通过数</td><td width="80" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">状态</td></tr>'
trs = ""
for i in range(len(groups)):
    tmp = tr.replace('分组信息',str(groups[i][0]))
    tmp = tmp.replace('用例总数', str(groups[i][1]))
    tmp = tmp.replace('通过数', str(groups[i][2]))
    tmp = tmp.replace('状态', str(groups[i][3]))
    trs += tmp

html = html.replace('mailbody',trs)
mail = Mail()
mail.send(html)

# 关闭加密
Encrypt.shutdown()

